package com.xiongkw.utils;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.*;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.text.ParseException;

public class FreemarkerUtil {
    //使用freemarker得到html内容
    public static String parseFtlFileTemplate(String ftlPath, String ftlName, Object context) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
        Version version = new Version("2.3.22");
        Configuration config = new Configuration(version);
        TemplateLoader templateLoader = new FileTemplateLoader( new File(ftlPath));
        config.setTemplateLoader(templateLoader);
        config.setDefaultEncoding("utf-8");
        Template tpl = config.getTemplate(ftlName);
        StringWriter writer = new StringWriter();
        tpl.process(context, writer);
        writer.flush();
        String html = writer.toString();
        return html;
    }


    public static String parseFtlStringTemplate(String ftlContent,Object context) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
        Version version = new Version("2.3.22");
        Configuration config = new Configuration(version);
        StringTemplateLoader templateLoader = new StringTemplateLoader();
        templateLoader.putTemplate("ftlTemplate",ftlContent);
        config.setTemplateLoader(templateLoader);
        config.setDefaultEncoding("utf-8");
        Template tpl = config.getTemplate("ftlTemplate");
        StringWriter writer = new StringWriter();
        tpl.process(context, writer);
        writer.flush();
        String html = writer.toString();
        return html;
    }
}
